package com.erbao.dp.proxy.v08;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Random;

interface Movable{
    void move();
}

class LogHandler implements InvocationHandler{
    Tank tank;

    public LogHandler(Tank tank) {
        this.tank = tank;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("method = "+method.getName()+" start");
        Object o = method.invoke(tank, args);
        System.out.println("method = "+method.getName()+" end");
        return o;
    }
}

/**
 * @author CaoBaoYin
 * @since 2021/9/16 21:52
 */
public class Tank implements Movable {
    @Override
    public void move() {
        System.out.println("tank moving calalalala……");
        // 模拟坦克移动时间
        try {
            Thread.sleep(new Random().nextInt(10000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Tank tank = new Tank();
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
        /*使用 被代理对象同一个类加载器 即可
        * 代理对象应该实现什么接口，被代理对象实现的接口
        * */
        Movable m = (Movable) Proxy.newProxyInstance(Tank.class.getClassLoader(), new Class[]{Movable.class}, new LogHandler(tank));

        m.move(); // 实际调用 handler的invoke方法
    }
}
